import {
  BaseCommand,
  CommandDialog,
  CommandDialogPlacement,
  EventsRes,
  ICurve,
  KEYBOARD_KEY,
  ObjInfo,
} from '@amcax/base';
import { ctx2 } from '@app-cad/module';

import { Button } from 'antd';
import i18n from 'i18next';
import { useEffect, useState } from 'react';

import { Picker2D, PickerMgr } from '@amcax/renderer';
import { CommandFormWrapper } from '@app-cad/common/components/command-form';
import { PickInputForFocus2D } from '@app-cad/common/components/command-form/auto-focus/pick-input';
import {
  basicSketchIds,
  renderSketch,
  sketchPreview,
} from '@app-cad/common/utils';
import { wsApi } from '@app-cad/server';
import {
  SKETCH_CENTEREVENTS,
  sketchEventCenter,
} from '../../../events/SketchEventCenter';

interface MirrorDialogProps {
  title: string;
  placement: CommandDialogPlacement;
  props: ObjInfo;
  onClose: () => void;
}
function MirrorDialog({ title, onClose }: MirrorDialogProps) {
  const [axisValue, setAxisValue] = useState([]);
  const [entityValue, setEntityValue] = useState([]);
  const sketchId = sketchEventCenter().getSketchInfo().sketchId;
  const picker = PickerMgr.getPicker<Picker2D>('2d');
  useEffect(() => {
    sketchEventCenter()
      .setState('mirror')
      .on(SKETCH_CENTEREVENTS.POINTERMOVE, mouseMove)
      .on(SKETCH_CENTEREVENTS.KEYUP, onKeyUp);
    return () => {
      sketchEventCenter()
        .setDefault()
        .off(SKETCH_CENTEREVENTS.POINTERMOVE, mouseMove);
      ctx2.cadScene.assisGroup.clear();
    };
  }, []);
  useEffect(() => {
    if (axisValue.length > 0 && entityValue.length > 0) {
      mirrorPreview();
    } else {
      ctx2.cadScene.assisGroup.clear();
    }
  }, [axisValue, entityValue]);
  const onKeyUp = (e: EventsRes<KeyboardEvent>) => {
    if (e.key === KEYBOARD_KEY.ESC) {
      onClose();
    }
  };
  const mouseMove = () => {};
  const onPickData = (ids: string[], picked: ICurve[]) => {
    if (picked.length === 0) {
      setAxisValue([]);
    } else if (picked && picked[0].type === 'Line') {
      setAxisValue(ids);
    }
  };
  const onEntityData = (ids: string[], picked: ICurve[]) => {
    if (picked.length === 0) {
      setEntityValue([]);
    } else {
      setEntityValue(ids);
    }
  };
  const handleMirrorSubmit = async () => {
    if (axisValue.length === 0 || entityValue.length === 0) {
      return;
    }
    const excludeValue = basicSketchIds;
    const entityData = entityValue.filter((item) => {
      return !excludeValue.includes(item);
    });
    const res = await wsApi.mirrorSketchCurves(
      sketchId,
      {
        curves: entityData,
        axis: axisValue[0],
      },
      false,
    );
    await renderSketch(sketchId, res);
    ctx2.cadScene.assisGroup.clear();
    picker.clickNull();
    onClose();
  };
  const mirrorPreview = async () => {
    // 坐标轴不做镜像
    const excludeValue = basicSketchIds;
    const entityData = entityValue.filter((item) => {
      return !excludeValue.includes(item);
    });
    const res = await wsApi.mirrorSketchCurves(
      sketchId,
      {
        curves: entityData,
        axis: axisValue[0],
      },
      true,
    );
    ctx2.cadScene.assisGroup.clear();
    sketchPreview(res.curves);
  };

  return (
    <CommandDialog
      title={title}
      placement='topLeft'
      className='sketchDialog'
      onClose={onClose}
    >
      <CommandFormWrapper>
        <PickInputForFocus2D
          value={axisValue}
          onPick={onPickData}
          controlled
          className='pick-input-mirror'
          placeholder='镜像线'
          autoFocus
        />
        <PickInputForFocus2D
          value={entityValue}
          onPick={onEntityData}
          controlled
          isMulti
          className='pick-input-mirror'
          placeholder='实体'
        />

        <div className='mirrorBtn'>
          <Button
            type='primary'
            onClick={handleMirrorSubmit}
            style={{ backgroundColor: '#464681' }}
          >
            完成
          </Button>
        </div>
      </CommandFormWrapper>
    </CommandDialog>
  );
}
export const cmdMirror: BaseCommand = {
  id: 'cmdMirror',
  label: 'command.mirror',
  icon: 'commands/sketch/mirror',
  group: 'sketch',
  create: (label: string, onClose: () => void, props) => (
    <MirrorDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
      placement='topLeft'
    />
  ),
};
